package cn.relx.system.service.impl;

import cn.relx.org.domain.Department;
import cn.relx.system.domain.Menu;
import cn.relx.system.mapper.MenuMapper;
import cn.relx.system.service.IMenuService;
import cn.relx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author relx
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> deptTree() {
        List<Menu> allDepts = menuMapper.findAll();
        // stream
        Map<Long, Menu> parentMap = allDepts.stream().collect(Collectors.toMap(Menu::getId, e -> e));
        // 同理
//        Map<Long, Department> parentMap = new HashMap<>();
//        for (Department dept : allDepts) {
//            parentMap.put(dept.getId(),dept);
//        }
        List<Menu> result = new ArrayList<>();
        // 遍历
        for (Menu dept : allDepts) {
            if (null == dept.getParentId()) {
                // 它就是最大的那个die
                result.add(dept);
            } else {
                // 当前的这个dept 是个儿子
                // 找爹 自己是个儿子 有爹的id
                Menu parent = parentMap.get(dept.getParentId());
                List<Menu> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }

}
